import AuthAPI from "@/api/auth";
import UserAPI from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";
import cloneDeep from "lodash/cloneDeep";
import { LoginData } from "@/api/auth/model";
import { UserInfo } from "@/api/user/model";
import { TOKEN_KEY } from "@/enums/CacheEnum";
import type { RouteRecord } from "vue-router";
import { asyncRoutes, constantRoutes, errorRoutes } from "@/router";
import router from "@/router";

const genAccessRoutes = (userRoutes: any, allAsyncRoutes: any) => {
  return allAsyncRoutes.filter((route: any) => {
    // 判断用户是否含有此路由的name标识
    if (userRoutes.includes(route.name)) {
      // 子路由也要对比
      if (route.children && route.children.length > 0) {
        route.children = genAccessRoutes(userRoutes, route.children);
      }
      return true;
    }
  });
};

export const useUserStore = defineStore("user", () => {
  const user = ref<Partial<UserInfo>>({});
  const menuRoutes = ref<RouteRecord[]>([]);

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.login(loginData)
        .then((data) => {
          const { tokenType, accessToken, refreshToken } = data;
          localStorage.setItem(TOKEN_KEY, tokenType + " " + accessToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          localStorage.setItem("refreshToken", tokenType + " " + refreshToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      UserAPI.getInfo()
        .then((data) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }

          Object.assign(user.value, { ...data });

          // 1.根据用户接口返回的菜单权限name名称，需要获取其在路由表中完整的信息
          // 注意：需要把动态路由进行深拷贝，否则会影响下一个登录用户的权限
          const userAccessRoutes = genAccessRoutes(
            user.value.routes,
            cloneDeep(asyncRoutes)
          );
          // 2.获取到完整的路由信息和常量路由进行合并,存入到pinia中
          menuRoutes.value = [
            ...constantRoutes,
            ...userAccessRoutes,
            ...errorRoutes,
          ];
          // 3.要加合并的路由信息动态的通过 router.addRoute() 添加到路由器中
          [...userAccessRoutes, ...errorRoutes].forEach((route) => {
            router.addRoute(route);
          });

          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      localStorage.setItem(TOKEN_KEY, "");
      location.reload(); // 清空路由
      resolve();

      //   AuthAPI.logout()
      //     .then(() => {
      //       localStorage.setItem(TOKEN_KEY, "");
      //       location.reload(); // 清空路由
      //       resolve();
      //     })
      //     .catch((error) => {
      //       reject(error);
      //     });
    });
  }

  // remove token
  function resetToken() {
    console.log("resetToken");
    return new Promise<void>((resolve) => {
      localStorage.setItem(TOKEN_KEY, "");
      localStorage.setItem("refreshToken", "");
      resetRouter();
      resolve();
    });
  }

  return {
    user,
    login,
    menuRoutes,
    getUserInfo,
    logout,
    resetToken,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
